package cn.kgc.jdbc;

import cn.kgc.entity.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author mosin
 * date 2022/2/10
 * @version 1.0
 * 插入一条数据 数据类型是对象 user
 */
public class JDBCDemo03 {


    public static void main(String[] args) {

        Connection connection = null;
        Statement stmt = null;
        try {
            //1.注册驱动  方式2  类加载  反射   推荐
            Class.forName("com.mysql.jdbc.Driver");
            //2.获取连接
            String  url = "jdbc:mysql://localhost:3306/java2114";
            String username = "root";
            String password = "root";
            connection = DriverManager.getConnection(url,username,password);
            //3. 生成操作数据库的对象
            stmt = connection.createStatement();
            // 4.编写sql  发送sql  DML insert  delete  update
            User user = new User();
            user.setRole(1);
            user.setPwd("888888");
            user.setUsername("lisi");
            String sql = "insert into user(username,pwd,role)values('"+user.getUsername()+"','"+user.getPwd()+"',"+user.getRole()+")";
            System.out.println("sql = " + sql);
            // 5. 处理结果集  DQL
            // 影响的行数
            int line = stmt.executeUpdate(sql);
            String result = line>0 ? "成功":"失败";
            System.out.println(result);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {  // 6. 释放资源

            try {
                if(stmt!=null){
                    stmt.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }

            try {
                if(connection!=null){
                    connection.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

    }


}
